import { Suspense } from 'react'
import { Switch, Redirect, Route, useHistory, useLocation, useRouteMatch } from 'react-router-dom'
import routes from "./routes"
import Loading from '@/components/Loading'

// 根据传递的name，获取需要迭代的路由表
const queryRoutesByName = (name) => {
    if (!name) return routes
    let arr = []
    const next = (routes) => {
        routes.forEach(item => {
            if (item.name === name) {
                arr = item.children || []
                return
            }
            if (item.children) {
                next(item.children)
            }
        })
    }
    next(routes)
    return arr
}

// 通用的路由匹配机制
const RouterView = function RouterView({ name }) {
    let arr = queryRoutesByName(name)
    if (!arr || arr.length === 0) return null
    return <Switch>
        {arr.map((item, index) => {
            let { path, component: Component, exact, redirect, meta = {} } = item
            let attrs = {
                history: useHistory(),
                location: useLocation(),
                match: useRouteMatch()
            }

            if (redirect) {
                // 重定向的规则
                let props = {}
                if (exact) props.exact = true
                if (path) props.from = path
                props.to = redirect
                return <Redirect key={index} {...props} />
            }
            // 正常匹配规则
            let props = {}
            if (exact) props.exact = true
            props.path = path
            return <Route key={index} {...props}
                render={() => {
                    // 在这里可以实现类似于vue-router中的导航守卫效果
                    let title = meta.title
                    document.title = title ? `OA管理系统 - ${title}` : `OA管理系统`

                    // fallback：在异步组件没有渲染出来之前，先展示fallback中的信息，异步组件渲染出来后，fallback中的信息就会销毁！
                    return <Suspense fallback={<Loading />}>
                        <Component {...attrs} />
                    </Suspense>
                }} />
        })}
        <Redirect to="/404" />
    </Switch>
}
RouterView.defaultProps = {
    name: ''
}
export default RouterView